/**
 * 
 */
package com.ekingstar.framework.security;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.FilterChain;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.Dispatcher;
import org.springframework.security.GrantedAuthority;
import org.springframework.web.filter.OncePerRequestFilter;

import com.opensymphony.xwork2.util.ValueStack;
import com.opensymphony.xwork2.util.ValueStackFactory;
import com.ekingstar.framework.domain.User;
import com.ekingstar.framework.service.IUserService;

/**
 * 
 *
 */
public class FunctionParameterValueFilter extends OncePerRequestFilter {

	private IUserService userService;
	public void setUserService(IUserService userService) {
		this.userService = userService;
	}
	protected void doFilterInternal(HttpServletRequest request,
			HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		String requestURI = request.getRequestURI();System.out.println("requesturi="+requestURI);
		String contextPath = request.getContextPath();System.out.println("contextPath="+contextPath);
		String pathInfo = request.getPathInfo();System.out.println("pathInfo="+pathInfo);
		String uri = request.getServletPath();System.out.println("servletpath="+uri);
        if (uri == null) {
            uri = requestURI;
            uri = uri.substring(contextPath.length());
        }
        System.out.println("uristr="+uri);
                
		User user = UserUtil.getCurrentUser();		
		if (user != null && user.getId() != null ){
			
			String reqAddress =  uri + ((pathInfo == null) ? "" : pathInfo);
	        String qs = request.getQueryString();
	        if (qs != null && !qs.trim().equals("")){
	        	reqAddress = reqAddress+"?"+qs;
	        }
	        
			Map params = userService.getUserFunctionParamValues(user.getId(), reqAddress);
			  
			if (params != null && !params.isEmpty()){
				//获取参数
				 ValueStack stack = (ValueStack) request.getAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY);
				 if (stack == null) {
			            Dispatcher du = Dispatcher.getInstance();
			            if (du != null) {
			            	 stack = du.getContainer().getInstance(ValueStackFactory.class).createValueStack();
			            }
				 }  
				 if (stack != null){
					 stack.getContext().put("userId", user.getId());
					 stack.getContext().put("sysData",sdf.format(new Date()));
					 GrantedAuthority[] ga =  user.getAuthorities();
					 if (ga != null && ga.length > 0){
						 List res = new ArrayList();
						 for (int i = 0;i < ga.length;i++){
							 res.add(ga[i].getAuthority());
						 }
						 stack.getContext().put("userRoles",res);
					 }
					
					 
				 }
				 
				request = new FunctionParamRequestWrapper(request,params,stack);
			}
			
		}
		else{
//			if(!uri.equals("/default.jsp")){
//				RequestDispatcher dispatch=request.getRequestDispatcher("/error.jsp");
//				dispatch.forward(request, response);
//				return;
//			}
		}
		
//		Map rm = request.getParameterMap();
//		String[] ps = (String[])rm.get("__parameters__");
//		if (ps != null && ps.length>0){
//			System.out.println(ps[0]);
//		}
		
		filterChain.doFilter(request, response);
		
	}
	private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
}
